package com.bwie.service.impl;

import cn.hutool.db.sql.Order;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.OrderInfoMapper;
import com.bwie.mapper.OrderMapper;
import com.bwie.pojo.TbDeliver;
import com.bwie.pojo.TbEnquiry;
import com.bwie.pojo.TbOderInfo;
import com.bwie.pojo.TbOrder;
import com.bwie.service.FeignService;
import com.bwie.service.OrderService;
import com.bwie.utils.R;
import com.bwie.vo.EsOrder;
import com.bwie.vo.PageVo;
import javassist.runtime.Desc;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title:
 * @BelongProjecet month0617
 * @BelongPackage com.bwie.service
 * @Description:
 * @Copyright 研发一部
 * @Author: Mr.yan
 * @Date: 2024/6/17 11:16
 * @Version V1.0
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private FeignService feignService;

    /**
     * @Description: //同步数据
     * @Auther: yanxingru
     * @Date: 2024/6/17 11:17
     * @param:
     * @return null
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void esOrderList(){
        //同步数据
        List<EsOrder> orderList = orderMapper.orderList();
        elasticsearchRestTemplate.save(orderList);
    }

    @Override
    public R esOrderList(PageVo pageVo) {
        //1.分页
        int pageNum = 0;
        if (pageVo.getPageNum() >0){
            pageNum = pageVo.getPageNum()-1;
        }
        PageRequest pageRequest = PageRequest.of(pageNum, pageVo.getPageSize());

        //2.设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>").postTags("</font>").field("goodsName");
        highlightBuilder.preTags("<font color='red'>").postTags("</font>").field("userName");

        //3.排序
        FieldSortBuilder sortBuilder = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);
        //4.查询
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //按照订单编号查询
        if (StringUtils.isNotEmpty(pageVo.getOrderNum())){
            boolQueryBuilder.must(
                    QueryBuilders.matchQuery("orderNum",pageVo.getOrderNum())
            );
        }
        //按照要货方查询查询
        if (pageVo.getEnquiryId()!=null){
            boolQueryBuilder.must(
                    QueryBuilders.matchQuery("enquiryId",pageVo.getEnquiryId())
            );
        }
        //按照发货方查询查询
        if (pageVo.getDeliverId()!=null){
            boolQueryBuilder.must(
                    QueryBuilders.matchQuery("deliverId",pageVo.getDeliverId())
            );
        }
        //按照商品编号查询
        if (StringUtils.isNotEmpty(pageVo.getGoodsNum())){
            boolQueryBuilder.must(
                    QueryBuilders.matchQuery("goodsNum",pageVo.getGoodsNum())
            );
        }
        //按照商品名称模糊查询
        if (StringUtils.isNotEmpty(pageVo.getGoodsName())){
            boolQueryBuilder.must(
                    QueryBuilders.matchQuery("goodsName",pageVo.getGoodsName())
            );
        }

        //根据状态查询
        if (pageVo.getOrderStatus()!=null && pageVo.getOrderStatus()!=5){
            boolQueryBuilder.must(
                    QueryBuilders.matchQuery("orderStatus",pageVo.getOrderStatus())
            );
        }

        //按照创建人模糊查询
        if (StringUtils.isNotEmpty(pageVo.getUserName())){
            boolQueryBuilder.must(
                    QueryBuilders.matchQuery("userName",pageVo.getUserName())
            );
        }
        //按照创建时间区间查询
        if (StringUtils.isNotEmpty(pageVo.getStartTime()) && StringUtils.isNotEmpty(pageVo.getEndTime())){
            boolQueryBuilder.must(
                    QueryBuilders.rangeQuery("createTime")
                            .format("yyyy-MM-dd HH:mm:ss")
                            .timeZone("GMT+8")
                            .gte(pageVo.getStartTime())
                            .lte(pageVo.getEndTime())
            );
        }

        //5.创建对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withHighlightBuilder(highlightBuilder)
                .withPageable(pageRequest)
                .withSort(sortBuilder)
                .withQuery(boolQueryBuilder);

        //6.查询
        SearchHits<EsOrder> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), EsOrder.class);
        long total = search.getTotalHits();

        //7.获取数据
        ArrayList<EsOrder> orderArrayList = new ArrayList<>();
        for (SearchHit<EsOrder> searchHit : search) {
            EsOrder esOrder = searchHit.getContent();
            List<String> goodsName = searchHit.getHighlightField("goodsName");
            if (goodsName!=null && goodsName.size()>0){
                esOrder.setGoodsName(goodsName.get(0));
            }

            if (esOrder.getOrderStatus() == 0){
                esOrder.setOrderSta("待审核");
            }
            if (esOrder.getOrderStatus() == 1){
                esOrder.setOrderSta("要货中");
            }
            if (esOrder.getOrderStatus() == 2){
                esOrder.setOrderSta("已完成");
            }
            if (esOrder.getOrderStatus() == 3){
                esOrder.setOrderSta("已驳回");
            }
            if (esOrder.getOrderStatus() == 4){
                esOrder.setOrderSta("已关闭");
            }
            orderArrayList.add(esOrder);
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("pageNum",pageNum);
        map.put("pageSize",pageVo.getPageSize());
        map.put("total",total);
        map.put("records",orderArrayList);

        return R.success(map);
    }

    @Override
    public R createIndex() {
        //判断索引是否存在
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(EsOrder.class);
        boolean exists = indexOperations.exists();
        if (exists){
            indexOperations.delete();
        }
        indexOperations.create();

        //创建映射
        Document mapping = indexOperations.createMapping();
        indexOperations.putMapping(mapping);
        return R.success();
    }

    @Override
    public R deliverFeign() {
        R r = feignService.deliverList();
        if (r.getCode() !=200){
            return r;
        }
        String s = JSON.toJSONString(r.getData());
        List<TbDeliver> deliverList = JSON.parseArray(s, TbDeliver.class);
        return R.success(deliverList);
    }

    @Override
    public R enquiryFeign() {
        R r = feignService.enquiryList();
        if (r.getCode() !=200){
            return r;
        }
        String s = JSON.toJSONString(r.getData());
        List<TbEnquiry> tbEnquiries = JSON.parseArray(s, TbEnquiry.class);
        return R.success(tbEnquiries);
    }

    @Override
    public R updateStatus(Integer id) {
        if (id!=null){
            return R.success();
        }

        //通过
        TbOrder tbOrder = orderMapper.selectOne(
                new QueryWrapper<TbOrder>().lambda().eq(TbOrder::getId,id)
        );
        tbOrder.setOrderStatus(2);
        orderMapper.updateById(tbOrder);
        return R.success();
    }

    @Override
    public R findById(Integer id) {
        TbOrder tbOrder = orderMapper.selectOne(
                        new QueryWrapper<TbOrder>().lambda().eq(TbOrder::getId,id)
                );
        return R.success(tbOrder.getFreeHtml());
    }
}
